<template>
  <view class="index">
    <view v-for="(question, index) in questionnaire.items" :key="index">
      <question
        v-if="index === currentQuestionIndex"
        :question="question"
        :total-question-count="questionnaire.items.length"
        :selected-questionnaire-items="selectedQuestionnaireItems"
        @onAnswer="onAnswerSelected"
      />
    </view>
    <view class="button-wrapper">
      <view
        class="questionnaire-button questionnaire-button--plain"
        @tap="prevQuestion"
        v-if="!isFirstQuestion"
        >上一题</view
      >
      <view
        class="questionnaire-button questionnaire-button--primary"
        :class="disabledNextQuestion ? 'disabled' : ''"
        @tap="nextQuestion"
        v-if="!isLastQuestion"
        >下一题</view
      >
      <view
        v-if="isCanSkip"
        class="questionnaire-button questionnaire-button--plain"
        @tap="skipQuestion"
        >跳过</view
      >
      <view
        class="questionnaire-button questionnaire-button--primary"
        :class="disabledNextQuestion ? 'disabled' : ''"
        @tap="getReport"
        v-if="isLastQuestion"
        >生成报告</view
      >
    </view>
  </view>
</template>

<script lang="ts">
import "./index.less";
import Taro from "@tarojs/taro";
import question from "../../components/question";
import { QuestionOption } from "../../../types";
import Vue from "vue";
import * as questionnaireService from "../../../services/questionnaire-service";

export default {
  components: {
    question
  },
  data() {
    return {
      questionnaire: null,
      currentQuestionIndex: 0,
      selectedQuestionnaireItems: []
    };
  },
  created() {
    this.$instance = Taro.getCurrentInstance();
    const type = this.$instance.router.params.type;
    this.questionnaire = this.$store.state.questionnaire.questionnaires.find(
      questionnaire => questionnaire.type === type
    );
  },
  computed: {
    isLastQuestion: function() {
      return this.currentQuestionIndex >= this.questionnaire.items.length - 1;
    },
    isFirstQuestion: function() {
      return this.currentQuestionIndex <= 0;
    },
    disabledNextQuestion() {
      const currentQuestion = this.questionnaire.items[
        this.currentQuestionIndex
      ];

      const selectedQuestionnaireItem = this.selectedQuestionnaireItems.find(
        item => item.id === currentQuestion.id
      );
      if (!selectedQuestionnaireItem) {
        return true;
      }
      const answers = selectedQuestionnaireItem.selectedOptions;
      return !answers || answers.length <= 0;
    },
    isCanSkip() {
      return this.questionnaire.items[this.currentQuestionIndex].skip;
    }
  },
  methods: {
    onAnswerSelected(selectedOption: QuestionOption) {
      this.addAnswerToCurrentQuestion(selectedOption);
    },
    addAnswerToCurrentQuestion(selectedOption: QuestionOption) {
      const currentQuestion = this.questionnaire.items[
        this.currentQuestionIndex
      ];

      let selectedQuestionnaireItem = this.selectedQuestionnaireItems.find(
        item => item.id === currentQuestion.id
      );
      if (!selectedQuestionnaireItem) {
        selectedQuestionnaireItem = currentQuestion;
        this.selectedQuestionnaireItems = [
          ...this.selectedQuestionnaireItems,
          selectedQuestionnaireItem
        ];
      }

      if (!selectedQuestionnaireItem.selectedOptions) {
        this.initQuestionSelectedOptions(selectedQuestionnaireItem);
      }
      // 单选插入值
      if (selectedQuestionnaireItem.type === "radio") {
        this.insertRadioSelectedOptions(
          selectedQuestionnaireItem,
          selectedOption
        );
      }

      // 多选插入值
      if (selectedQuestionnaireItem.type === "checkbox") {
        this.insertCheckboxSelectedOptions(
          selectedQuestionnaireItem,
          selectedOption
        );
      }
    },
    initQuestionSelectedOptions(currentQuestion) {
      Vue.set(currentQuestion, "selectedOptions", []);
    },
    insertRadioSelectedOptions(
      currentQuestion,
      selectedOption: QuestionOption
    ) {
      Vue.set(currentQuestion, "selectedOptions", [selectedOption]);
    },
    insertCheckboxSelectedOptions(
      currentQuestion,
      selectedOption: QuestionOption
    ) {
      const hasSelectedOptions = currentQuestion.selectedOptions.some(
        option => option.id === selectedOption.id
      );
      if (hasSelectedOptions) {
        Vue.set(
          currentQuestion,
          "selectedOptions",
          currentQuestion.selectedOptions.filter(
            option => option.id !== selectedOption.id
          )
        );
      } else {
        const exclusive = selectedOption.exclusive;
        // 互斥选项
        if (exclusive) {
          Vue.set(currentQuestion, "selectedOptions", [selectedOption]);
        } else {
          Vue.set(currentQuestion, "selectedOptions", [
            ...currentQuestion.selectedOptions,
            selectedOption
          ]);
        }
      }
    },
    nextQuestion() {
      if (this.disabledNextQuestion) {
        return;
      }
      this.currentQuestionIndex++;
    },
    prevQuestion() {
      const currentQuestion = this.questionnaire.items[
        this.currentQuestionIndex
      ];
      this.selectedQuestionnaireItems = this.selectedQuestionnaireItems.filter(
        item => item.id !== currentQuestion.id
      );
      this.currentQuestionIndex--;
    },
    skipQuestion() {
      const currentQuestion = this.questionnaire.items[
        this.currentQuestionIndex
      ];
      this.selectedQuestionnaireItems = this.selectedQuestionnaireItems.filter(
        item => item.id !== currentQuestion.id
      );
      this.currentQuestionIndex++;
    },
    async getReport() {
      if (this.disabledNextQuestion) {
        return;
      }

      // 根据问卷生成报告
      await questionnaireService.generateReport({
        ...this.questionnaire,
        items: this.selectedQuestionnaireItems
      });
      this.gotoReportPage();
    },
    gotoReportPage() {
      Taro.navigateTo({
        url: `/pages/health-questionnaire/report/index?pageId=${this.questionnaire.id}`
      });
    }
  },

  // onLoad
  onLoad() {},

  // onReady
  onReady() {},

  // 对应 onShow
  onShow() {},

  // 对应 onHide
  onHide() {},

  // 对应 onPullDownRefresh
  onPullDownRefresh() {}
};
</script>
<style lang="less">
@import "./src/styles/colors";

.questionnaire-button {
  padding: 32px;
  text-align: center;
  border-radius: 50px;
  font-size: 30px;

  &--primary {
    color: white;
    background: @purple100;
    flex-grow: 10;
  }

  &--plain {
    color: @purple100;
    background-color: #fff;
    flex-grow: 1;
    border: 1px solid @purple100;
  }

  &:not(:last-child) {
    margin-right: 30px;
  }
}

.button-wrapper {
  display: flex;
  justify-content: space-between;
  padding: 48px;
}
</style>
